package com.bjpowernode.web.handler;

import com.bjpowernode.constants.enums.Code;
import com.bjpowernode.web.resp.ResponseObj;
import org.apache.commons.logging.Log;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 麦翔盛
 * @ClassName: GlobalExceptionHandler
 * @Package: com.bjpowernode.web.handler
 * @description: 全局异常处理类
 * 全局异常处理类会从上到下依次遍历查找匹配的异常处理类
 * @date 2022/6/2 15:06
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理算术异常
     * @param ex 异常
     * @return
     */
    @ExceptionHandler(value = {ArithmeticException.class})
    public ResponseObj doArithmeticException(ArithmeticException ex){
        //打印日志
        System.out.println("异常为:" + ex.getMessage());
        return ResponseObj.error(Code.ZERO_FAIL);
    }

    /**
     * 处理空指针异常
     * @param ex 异常
     * @return
     */
    @ExceptionHandler(value = {NullPointerException.class})
    public ResponseObj doNullPointerException(NullPointerException ex){
        System.out.println("异常为:" + ex.getMessage());
        return ResponseObj.error(Code.NULL_ERROR);
    }

    /**
     * 如果没有添加指定异常 就会拦截所有到这里的异常
     * @param e 异常
     * @return
     */
    @ExceptionHandler
    public ResponseObj doOtherException(Exception e){
        System.out.println("未知异常为:" + e.getMessage());
        return ResponseObj.error(Code.OTHER_ERROR);
    }


}
